<template>
  <div>
    <el-form>
      <el-form-item label="SPU名称">
        <el-input placeholder="请你输入SPU名称" size="default" v-model="spuparams.spuName"></el-input>
      </el-form-item>
      <el-form-item label="SPU品牌">
        <el-select placeholder="请选择某一个品牌" v-model="spuparams.tmId">
          <el-option
            :label="trademark.tmName"
            :value="trademark.id"
            v-for="(trademark) in tradmarklist"
            :key="trademark.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="SPU描述">
        <el-input type="textarea" placeholder="请你输入SPU描述" v-model="spuparams.description"></el-input>
      </el-form-item>
      <el-form-item label="SPU图片">
        <el-upload
          v-model:file-list="spuimagelist"
          action="/app-dev/admin/product/fileUpload"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
        >
          <el-icon>
            <Plus />
          </el-icon>
        </el-upload>

        <el-dialog v-model="dialogVisible">
          <img w-full :src="dialogImageUrl" alt="Preview Image" style="width:100%" />
        </el-dialog>
      </el-form-item>
      <el-form-item label="销售属性">
        <el-select
          clearable
          :placeholder="unSelectAttrList.length==0?`空`:`还有${unSelectAttrList.length}项未选择`"
          @change="change"
          v-model="selectedAttr"
        >
          <el-option
            :value="attr.id"
            :label="attr.name"
            v-for="attr in unSelectAttrList"
            :key="attr.id"
          ></el-option>
        </el-select>
        <el-button
          style="margin-left:10px"
          type="primary"
          size="default"
          :icon="Plus"
          :disabled="selectedAttr==''"
          @click="addAttr"
        >添加销售属性</el-button>
      </el-form-item>
      <el-table border stripe style="margin:10px 0px" :data="spuattrlist">
        <el-table-column label="序号" width="90" align="center" type="index" :resizable="false"></el-table-column>
        <el-table-column label="销售属性名称" width="120" :resizable="false" prop="saleAttrName"></el-table-column>
        <el-table-column label="销售属性值名称" :resizable="false">
          <template #="{row,$index}">
            <el-tag
              style="margin-right:10px;margin-top:5px"
              :type="choiceOne(attList)"
              closable
              v-for="(attrval,index) in row.spuSaleAttrValueList"
              :key="attrval.id"
              @close="delAttrValue(row,index)"
            >{{ attrval.saleAttrValueName}}</el-tag>

            <el-button
              type="primary"
              size="small"
              :icon="Plus"
              v-if="!row.show"
              @click="toEdit(row,$index)"
            ></el-button>
            <el-input
              size="small"
              v-else
              style="width:100px;display:inline-block;margin-right:10px;"
              :ref="(el)=>(inputListRef[$index]=el)"
              @blur="toLook(row)"
              v-model="row.attrValue"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" :resizable="false">
          <template #="{row}">
            <el-button type="danger" size="small" :icon="Delete" @click="delAttr(row)"></el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-button type="primary" size="default" :disabled="spuattrlist.length==0" @click="save">保存</el-button>
      <el-button @click="cancel">取消</el-button>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, nextTick } from 'vue'
import { Plus, Delete } from '@element-plus/icons-vue'

import type { UploadProps } from 'element-plus'
import { ElMessage } from 'element-plus'
import { choiceOne } from '../attr/tool'
import {
  reqTradmarkList,
  reqSpuImageList,
  reqSpuAttrList,
  reqBaseAttrList,
  reqUpdateSpu,
  reqSaveSpu
} from '@/api/product/spu/index'
const $emit = defineEmits(['changeSene'])
const attList = ['success', 'info', 'warning', 'danger']
const tradmarklist = ref<any>()
const spuimagelist = ref<any>()
const spuattrlist = ref<any>([])
const baseattrlist = ref<any>([])
const selectedAttr = ref<any>('')
const attrVal = ref<any>('')
const inputListRef = ref<any>([])
const spuparams = ref<any>({
  category3Id: '',
  description: '',
  // id: '',
  spuImageList: null,
  spuName: '',
  spuSaleAttrList: null,
  tmId: '',
})

const dialogImageUrl = ref('')
const dialogVisible = ref(false)

const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles)
}

const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}

const cancel = () => {
  $emit('changeSene',spuparams.value.id?{seneNum:1, addOrUpdateFlag:'update'}:{seneNum:1, addOrUpdateFlag:'add'})
  selectedAttr.value=''
}
const reqSpuInfoData = async (row: any) => {
  // console.log('子组件接收row',row)
  tradmarklist.value = await reqTradmarkList()
  const imageList: any = await reqSpuImageList(row?.id)
  spuimagelist.value = imageList.map((item: any) => {
    return {
      name: item.imgName,
      url: item.imgUrl,
    }
  })
  spuattrlist.value = await reqSpuAttrList(row.id)
  baseattrlist.value = await reqBaseAttrList()
  spuparams.value = row
}

const unSelectAttrList = computed(() => {
  let result = baseattrlist.value.filter((item: any) => {
    return !spuattrlist.value.find((item1: any) => {
      return item1.saleAttrName == item.name
    })
  })
  return result
})

const addSpuInit = async(cate3Id:number|string)=>{
   spuparams.value.category3Id = cate3Id
   tradmarklist.value = await reqTradmarkList()
   baseattrlist.value = await reqBaseAttrList()
  spuparams.value.description=''
  spuparams.value.spuImageList =null
  spuparams.value.spuName = ''
  spuparams.value.spuSaleAttrList =null
  spuparams.value.tmId = ''
  spuimagelist.value= []
  spuattrlist.value= []
  spuparams.value.id = ''
}

defineExpose({
  reqSpuInfoData,
  addSpuInit
})

const change = (val: any) => {
  console.log(val)
}

const addAttr = () => {
  const { name, id } = unSelectAttrList.value.find((item: any) => {
    return selectedAttr.value == item.id
  })
  const attrObj = {
    baseSaleAttrId: id,
    saleAttrName: name,
    spuId: spuparams.value.id,
    spuSaleAttrValueList: [],
  }
  spuattrlist.value.push(attrObj)
  selectedAttr.value = ''
}

const toEdit = (row: any,$index:number) => {
  row.show = true
  row.attrValue = ''
  nextTick(()=>{
      inputListRef.value[$index].focus()
  })

}

const toLook = (row: any) => {
  const attrValObj = {
    baseSaleAttrId: row.baseSaleAttrId,
    saleAttrName: row.saleAttrName,
    saleAttrValueName: row.attrValue,
    spuId: row.spuId,
  }
  if (attrValObj.saleAttrValueName.trim() == '') {
    return ElMessage({ type: 'error', message: '属性值不能为空' })
  }
  if (
    row.spuSaleAttrValueList.find((item: any) => {
      return item.saleAttrValueName == attrValObj.saleAttrValueName
    })
  ) {
    return ElMessage({ type: 'error', message: '属性值重复' })
  }
  row.spuSaleAttrValueList.push(attrValObj)
  row.show = false
}
const delAttrValue = (row: any, index: any) => {
  row.spuSaleAttrValueList.splice(index, 1)
}
const delAttr = (row: any) => {
  spuattrlist.value = spuattrlist.value.filter((item: any) => {
    return item != row
  })
}
const save = async () => {
  const imageList = spuimagelist.value?.map((item: any) => {
    return {
      imgName: item.name,
      imgUrl: item.response? item.response.data:item.url,
    }
  })
  spuparams.value.spuImageList = imageList
  spuparams.value.spuSaleAttrList = spuattrlist.value
  try {
     spuparams.value.id ? await reqUpdateSpu(spuparams.value): await reqSaveSpu(spuparams.value)
     ElMessage({
      type:'success',
      message: spuparams.value.id?'更新成功':'添加成功'
     })
     
     spuparams.value.id ? $emit('changeSene',{seneNum:1, addOrUpdateFlag:'update'}):$emit('changeSene',{seneNum:1, addOrUpdateFlag:'add'})
     selectedAttr.value= ''
  } catch (error) {
    ElMessage({
      type:'error',
      message: spuparams.value.id?'更新失败':'添加失败'
     })
  }
}
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>